package com.zhilong;

import org.json.JSONObject;

import android.app.Activity;
import android.widget.Toast;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class SessionMgr {
	private static Session currentSession = new Session();
	
	public static Session getCurrentSession()
	{
		return currentSession;
	}
	
	public static class Session
	{
		private String id = null;
		private User currentUser = null;
	    private Tencent mTencent = null;
	    private String APP_ID = "100386331";

	    public Session()
	    {
	        mTencent = Tencent.createInstance(APP_ID, App.getAppContext());
	    }
	    
		public User getCurrentUser() {
			return currentUser;
		}

		public void setCurrentUser(User currentUser) {
			this.currentUser = currentUser;
		}
		
		public void login(Activity activity)
		{
			if(this.isLoggedIn())
				return;
			
			if (!mTencent.isSessionValid()) {
	            IUiListener listener = new BaseUiListener() {
	                @Override
	                protected void doComplete(JSONObject values) {
	                	setLoggedIn(true);
	                    Toast.makeText(App.getAppContext(), "Return: " + values.toString(), Toast.LENGTH_SHORT);
	                }
	            };
	            mTencent.login(activity, "all", listener);
	        } 
		}

		private int uid = 0;
		public int getUid() {
			return uid;
		}

		public void setUid(int uid) {
			this.uid = uid;
		}

		private boolean isLoggedin = false;
		
		public void setId(String id)
		{
			this.id = id;
		}
		
		public String getId()
		{
			return this.id;
		}
		
		public void setLoggedIn(boolean loggedIn)
		{
			this.isLoggedin = loggedIn;
		}
		
		public boolean isLoggedIn()
		{
			return this.isLoggedin;
		}
		
	    private class BaseUiListener implements IUiListener {

	        @Override
	        public void onComplete(JSONObject response) {
	            doComplete(response);
	        }

	        protected void doComplete(JSONObject values) {

	        }

	        @Override
	        public void onError(UiError e) {
	            Toast.makeText(App.getAppContext(), "code:" + e.errorCode + ", msg:" + e.errorMessage + ", detail:" + e.errorDetail, Toast.LENGTH_SHORT);
	        }

	        @Override
	        public void onCancel() {
	        }
	    }
	}
}
